<?php
class App{
    //禁止实例化
    private function __construct(){}
    
    //应用初始化
    public static function init(){
                
        //加载用户扩展函数库
        if(is_file(FUN_PATH.'extend.php')) {
            include FUN_PATH.'extend.php';
        }
        
        if(!get_magic_quotes_gpc()) {
            $_POST = new_addslashes($_POST);
            $_GET = new_addslashes($_GET);
            $_REQUEST = new_addslashes($_REQUEST);
            $_COOKIE = new_addslashes($_COOKIE);
        }
        
        new Route;//路由实例化
    }
    
    // 执行应用程序
     public static function exec() {
         //检测模块是否存在
         if(M_NAME&&preg_match('/^[A-Za-z]+$/',M_NAME)&&is_dir(APP_PATH.'modules'.DS.M_NAME)){
             define('M_PATH', APP_PATH .'modules'.DS.M_NAME.DS);
             //加载模块配置文件
             if(is_dir(M_PATH.'config')){
                 $config_files=scandir(M_PATH.'config');
                 if($config_files!==false&&is_array($config_files)){
                     foreach ($config_files as $v){
                         if(strpos($v,'.php')!==false){
                             C(include M_PATH.'config'.DS.$v);
                         }
                     }
                 }
             }
             
             //if(is_file(M_PATH.'config'.DS.'config.php')) C(include M_PATH.'config'.DS.'config.php');
             //加载模块函数库
             if(is_file(M_PATH.'function'.DS.'function.php'))  include M_PATH.'function'.DS.'function.php';
         }
         else  throw new Exception(M_NAME.'模块不存在',404);
         
        if(preg_match('/^[A-Za-z_]+$/',C_NAME)&&is_file(M_PATH.C_NAME.'.class.php')){
            include M_PATH.C_NAME.'.class.php';
            $class=C_NAME;
            if (class_exists($class)) {
                $controller=new $class();
            }
        }else{
            $controller  =  false;
        }
        if(!$controller) {//如果没有该控制器则加载404
            throw new Exception(C_NAME.'控制器加载失败',404);
        }
        try{
            $method =   new ReflectionMethod($controller, A_NAME);
            if($method->isPublic() && !$method->isStatic()) {
                $method->invoke($controller);//执行方法
            }
 
        } catch (ReflectionException $e) {
            $method = new ReflectionMethod($controller,'__call');
            $method->invokeArgs($controller,array(A_NAME,''));
        }
        return ;
    }
    
    //应用执行
    public static  function run(){
            App::init();
            App::exec();
            return;
    }
}